<?php

namespace App\Models\OpenShop\InvestmentPromotion;

use App\Enums\OpenShop\InvestmentPromotion\SignOrderEnum;
use App\Enums\OpenShop\InvestmentPromotion\UserContractEnum;
use App\Models\BaseModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use App\Support\ChangeSupport;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\DB;

class OpenShopUserContractModel extends BaseModel
{
    use KfUid;
    use KfSoftDeletes;

    protected $table = 'open_shop_user_contract';

    const CONTRACT_STATUS_NORMAL  = 0;
    const CONTRACT_STATUS_INVALID = 1;

    const CONTRACT_STATUS_TYPE = [
        self::CONTRACT_STATUS_NORMAL  => "正常",
        self::CONTRACT_STATUS_INVALID => "作废"
    ];


    protected $fillable = [
        'orderNo',
        'remark',
        'createdAt',
        'updatedAt',
        'refundDecorationDeposit',
        'contractExtNo',
        'version',
        'guidanceFee',
        'isDeleted',
        'contractStatus',
        'companyName',
        'address',
        'businessLicenseImg',
        'legalPerson',
        'businessLicenseNumber',
        'businessLicenseContent',
        'mode',
        'content',
        'inviterId',
        'inviterName',
        'departmentName',
        'detailStatus',
        'categoryName',
        'categoryId',
        'signTime',
        'depositAmountRatio',
        'monthRealAmountCommissionCapping',
        'isCommissionCapping',
        'amountCommissionCapping',
        'depositAmount',
        'shopCount',
    ];

    /**
     * 开店合同集合 【续签合同、新店新开、老店裂变等】
     */
    const OPEN_SHOP_CONTRACT_GROUP = [
        UserContractEnum::CONTRACT_TYPE_8,
        UserContractEnum::CONTRACT_TYPE_1,
        UserContractEnum::CONTRACT_TYPE_2,
        UserContractEnum::CONTRACT_TYPE_9,
    ];

    public static function getOrderLogTranslate()
    {
        return [
            'orderNo'                          => '订单号',
            'contractors'                      => '签约主题',
            'companyName'                      => '公司名称',
            'businessLicenseNumber'            => '营业执照号',
            'address'                          => '营业执照',
            'startTime'                        => [
                "type" => ChangeSupport::FILED_TYPE_DATE_YMD,
                "desc" => "合同开始时间"
            ],
            'endTime'                          => [
                "type" => ChangeSupport::FILED_TYPE_DATE_YMD,
                "desc" => "合同截止时间"
            ],
            'contractType'                     => [
                "type" => ChangeSupport::FILED_TYPE_ENUM,
                "enum" => UserContractEnum::CONTRACT_TYPE,
                "desc" => "签约类型"
            ],
            'policyTemplateId'                 => '政策模版id',
            'remark'                           => '内部备注',
            'initialFee'                       => [
                "type" => ChangeSupport::FILED_TYPE_PRICE,
                "desc" => "加盟费"
            ],
            'technologyTransferFee'            => [
                "type" => ChangeSupport::FILED_TYPE_PRICE,
                "desc" => "技术转让费"
            ],
            'deposit'                          => [
                "type" => ChangeSupport::FILED_TYPE_PRICE,
                "desc" => "保证金"
            ],
            'managementCost'                   => [
                "type" => ChangeSupport::FILED_TYPE_PRICE,
                "desc" => "特许权使用费第一年"
            ],
            'managementCostEveryYear'          => [
                "type" => ChangeSupport::FILED_TYPE_PRICE,
                "desc" => "特许权使用费(每年)"
            ],
            'decorationDeposit'                => [
                "type" => ChangeSupport::FILED_TYPE_PRICE,
                "desc" => "装修保证金"
            ],
            'shopCount'                        => '店铺数量',
            'year'                             => '合同年限',
            'mode'                             => [
                "type" => ChangeSupport::FILED_TYPE_ENUM,
                "enum" => OpenShopContractTemplateModel::MODE_MAP_TEXT,
                "desc" => "加盟模式"
            ],
            'inviterId'                        => '签约推荐人',
            'departmentName'                   => '签约推荐人所在部门',
            'content'                          => '分账抽佣比例',//分账模式信息
            'depositAmountRatio'               => '每月实收抽佣比例', // 分账模式信息
            'monthRealAmountCommissionCapping' => '月实收抽佣封顶金额', // 分账模式信息
            'isCommissionCapping'              => '是否抽佣累计封顶', // 分账模式信息
            'amountCommissionCapping'          => '抽佣累计封顶金额', // 分账模式信息
            'depositAmount'                    => '定金金额', // 定金模式信息
        ];
    }

    /**
     * @return HasOne
     */
    public function templateRel(): HasOne
    {
        return $this->hasOne(OpenShopContractTemplateModel::class, 'id', 'policyTemplateId');
    }

    public function mainProcessRel(): HasOne
    {
        return $this->hasOne(OpenShopMainProcessModel::class, 'orderNo', 'orderNo');
    }

    /**
     * @return HasMany
     */
    public function userExtContractRel(): HasMany
    {
        return $this->hasMany(OpenShopUserExtContractModel::class, 'contractId', 'id');
    }

    /**
     * 返回金额模板的对应金额列表-H5支付页面
     * @return array
     */
    public function costLists(): array
    {
        $res = [];

        switch ($this->version) {
            case 2:
                $initialFeeName            = '品牌使用费';
                $technologyTransferFeeName = '经营技术授予费';
                break;
            default:
                $initialFeeName            = '加盟费';
                $technologyTransferFeeName = '技术转让费';
        }

        foreach ($this->toArray() as $column => $v) {
            switch ($column) {
                case "initialFee":
                    $res[] = [
                        'name'      => $initialFeeName,
                        'price'     => $v,
                        'canRefund' => 0,
                    ];
                    break;
                case "technologyTransferFee":
                    $res[] = [
                        'name'      => $technologyTransferFeeName,
                        'price'     => $v,
                        'canRefund' => 0,
                    ];
                    break;
                case "guidanceFee":
                    $res[] = [
                        'name'      => '咨询指导服务费',
                        'price'     => $v,
                        'canRefund' => 0,
                    ];
                    break;
                case "managementCost":
                    $res[] = [
                        'name'      => '特许权使用费第一年',
                        'price'     => $v,
                        'canRefund' => 0,
                    ];
                    break;
                case "deposit":
                    $res[] = [
                        'name'      => '保证金',
                        'price'     => $v,
                        'canRefund' => 1,
                    ];
                    break;
                case "decorationDeposit":
                    $res[] = [
                        'name'      => '装修保证金',
                        'price'     => $v,
                        'canRefund' => 1,
                    ];
                    break;
                default:
                    break;
            }
        }

        return $res;
    }


    /**
     * 返回金额模板的对应金额列表-H5支付页面
     * @return array
     */
    public function signOrderCostLists(): array
    {
        $res = [];

        switch ($this->version) {
            case 2:
                $initialFeeName            = '品牌使用费';
                $technologyTransferFeeName = '经营技术授予费';
                break;
            default:
                $initialFeeName            = '加盟费';
                $technologyTransferFeeName = '技术转让费';
        }

        foreach ($this->toArray() as $column => $v) {
            switch ($column) {
                case "initialFee":
                    $res['initialFee'] = [
                        'name'      => $initialFeeName,
                        'price'     => $v,
                        'canRefund' => 0,
                    ];
                    break;
                case "technologyTransferFee":
                    $res['technologyTransferFee'] = [
                        'name'      => $technologyTransferFeeName,
                        'price'     => $v,
                        'canRefund' => 0,
                    ];
                    break;
                case "guidanceFee":
                    $res['guidanceFee'] = [
                        'name'      => '咨询指导服务费',
                        'price'     => $v,
                        'canRefund' => 0,
                    ];
                    break;
                case "managementCost":
                    $res['managementCost'] = [
                        'name'      => '特许权使用费第一年',
                        'price'     => $v,
                        'canRefund' => 0,
                    ];
                    break;
                case "deposit":
                    $res['deposit'] = [
                        'name'      => '保证金',
                        'price'     => $v,
                        'canRefund' => 1,
                    ];
                    break;
                case "decorationDeposit":
                    $res['decorationDeposit'] = [
                        'name'      => '装修保证金',
                        'price'     => $v,
                        'canRefund' => 1,
                    ];
                    break;
                default:
                    break;
            }
        }
        return $res;
    }

    /**
     * 获取图片信息
     *
     * @return string
     */
    public function getBusinessLicenseFullImg()
    {
        return picturePath($this->businessLicenseImg);
    }

    public static function getUserIdByOrderNo($bizId)
    {
        return OpenShopUserContractModel::query()
                                        ->where('orderNo', $bizId)
                                        ->value('id');
    }

    private static function getRefundDecorationDepositOrderBuilder(string $orderNoRawSql)
    {
        // 查找完成了的订单
        $orderList = OpenShopSignOrderModel::query()->where('status', SignOrderEnum::ORDER_STATUS_COMPLETE)
                                           ->pluck('orderNo');

        return OpenShopUserContractModel::query()
                                        ->whereIn('orderNo', $orderList)
                                        ->when($orderNoRawSql, function ($query) use ($orderNoRawSql) {
                                            $query->whereRaw($orderNoRawSql);
                                        })
                                        ->where('decorationDeposit', '!=', DB::raw('refundDecorationDeposit'))
                                        ->where('decorationDeposit', '<>', 0)
                                        ->where('updatedAt', '<>', 0)
                                        ->distinct('orderNo')
                                        ->where('createdAt', '<>', 0);
    }

    /**
     * 查询装修保证金待退
     */
    public static function getRefundDecorationDepositOrderCount(string $orderNoRawSql)
    {
        return self::getRefundDecorationDepositOrderBuilder($orderNoRawSql)->count();
    }

    public static function getRefundDecorationDepositOrderCountOrderNos(string $orderNoRawSql)
    {
        return self::getRefundDecorationDepositOrderBuilder($orderNoRawSql)->pluck('orderNo');

    }

    /**
     * @return HasOne
     */
    public function signOrderRel(): HasOne
    {
        return $this->hasOne(OpenShopSignOrderModel::class, "orderNo", "orderNo");
    }

    public static function copyRow(string $orderNo)
    {
        $userContractModel = self::query()
                                 ->where("orderNo", $orderNo)
                                 ->whereIn("contractType",
                                    OpenShopUserContractModel::OPEN_SHOP_CONTRACT_GROUP)
                                 ->orderBy("id", "desc")
                                 ->first();

        $copyData = collect($userContractModel->toArray())->except([
            "id",
            "detailStatus",
            "signTime",
            "contractExtNo",
            "exceptionMsg",
            "contractStatus"
        ])->merge(["createdAt" => time(), "updatedAt" => time()])->toArray();

        OpenShopUserContractModel::query()->insert($copyData);
    }

    public static function invalidOrderCopyRow(string $orderNo, int $contractType)
    {
        $userContractModel = self::query()
                                 ->where("orderNo", $orderNo)
                                 ->first();

        $copyData = collect($userContractModel->toArray())->except([
            "id",
            "contractExtNo",
            "exceptionMsg",
            "contractStatus"
        ])->merge([
            "contractType" => $contractType,
            "createdAt"    => time(),
            "updatedAt"    => time()
        ])->toArray();

        return OpenShopUserContractModel::query()->insertGetId($copyData);
    }

    /**
     * @param string $contractId
     * @return Builder|Model|object|null
     */
    public static function getUserContractByContractExtNo(string $contractId)
    {
        return self::query()->where("contractExtNo", $contractId)->first();
    }

    /**
     * 获取订单合同
     *
     * @param string $orderNo
     * @param array $contractType
     * @return array|Builder[]|Collection
     */
    public static function getUserContract(string $orderNo, array $contractType = [])
    {
        return self::query()
                   ->where("orderNo", $orderNo)
                   ->when(count($contractType) > 0, function ($query) use ($contractType) {
                       $query->whereIn("contractType", $contractType);
                   })->get();
    }

    /**
     * 获取用户合同
     *
     * @param string $orderNo
     * @return Builder|Model|object|null
     */
    public static function getUserContractDetail(string $orderNo)
    {
        return OpenShopUserContractModel::query()
                                        ->where("orderNo", $orderNo)
                                        ->with([
                                            "signOrderRel",
                                            "mainProcessRel" => function ($query) {
                                                $query->with([
                                                    "userIdentityCardRel",
                                                    "userContractRel",
                                                    "userBaseInfoRel",
                                                    "userExperienceRel"
                                                ]);
                                            }
                                        ])->first();
    }

    /**
     * 生成网商分账配置 - 后台展示用，仅过渡使用！！！！
     * @return array
     */
    public function getMyBankShareConfigShow(): array
    {
        // 分佣比例配置
        $getBrokerageConfig = [];
        if (in_array($this->mode, [OpenShopContractTemplateModel::MODE_2])) {
            $getBrokerageConfig[] = [
                'startPrice' => 0,
                'endEqPrice' => $this->monthRealAmountCommissionCapping,
                'type'       => 'percent',
                'percent'    => (float)$this->depositAmountRatio,
            ];

            if ($this->monthRealAmountCommissionCapping != 999000000) {
                $getBrokerageConfig[] = [
                    'startPrice' => $this->monthRealAmountCommissionCapping,
                    'endEqPrice' => 999000000,
                    'type'       => 'percent',
                    'percent'    => 0,
                ];
            }
        }

        return $getBrokerageConfig;
    }

    /**
     * 生成网商分账配置
     * @return array
     */
    public function getMyBankShareConfig(): array
    {
        if (!in_array($this->mode, [OpenShopContractTemplateModel::MODE_2])) {
            return [];
        }

        // 月实封顶
        $monthRealAmountCommissionCapping = $this->monthRealAmountCommissionCapping;
        if ($this->monthRealAmountCommissionCapping == 0) {
            $monthRealAmountCommissionCapping = 999000000;
        }

        // 分佣比例配置
        $rule   = [];
        $rule[] = [
            'startPrice' => 0,
            'endEqPrice' => $monthRealAmountCommissionCapping,
            'type'       => 'percent',
            'percent'    => (float)$this->depositAmountRatio,
        ];

        if ($monthRealAmountCommissionCapping != 999000000) {
            $rule[] = [
                'startPrice' => $this->monthRealAmountCommissionCapping,
                'endEqPrice' => 999000000,
                'type'       => 'percent',
                'percent'    => 0,
            ];
        }

        // 抽佣累计封顶
        $stopRule = [];
        if ($this->isCommissionCapping) {
            $stopRule = [
                'totalAmount' => $this->amountCommissionCapping,
            ];
        }

        return [
            'rule'      => $rule,
            'isStop'    => false,
            'isPause'   => false,
            'pauseRule' => [],
            'stopRule'  => $stopRule,
        ];
    }
}
